﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Devsoft.Web.Mvc.Cache
{
    public class InMemoryCache : ICacheService,IDisposable
    {
        private static InMemoryCache _instance;

        public static InMemoryCache Default
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new InMemoryCache();
                }
                return _instance;
            }
        }

        public void Remove(string cacheID)
        {
            HttpRuntime.Cache.Remove(cacheID);
        }
            

        public  T Get<T>(string cacheID, Func<T> getItemCallback,int minuteToExpire = 0) where T : class
        {
            T item = HttpRuntime.Cache.Get(cacheID) as T;
            if (item == null)
            {
                item = getItemCallback();
                if (minuteToExpire < 1)
                {
                    HttpRuntime.Cache.Insert(cacheID, item);    
                }
                else
                {
                    HttpRuntime.Cache.Insert(cacheID, item, null, DateTime.Now.AddMinutes(minuteToExpire), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);    
                }
            }
            return item;
        }

        public void Dispose()
        {
            
        }
    }

    public interface ICacheService
    {
        T Get<T>(string cacheID, Func<T> getItemCallback, int minuteToExpire = 0) where T : class;
    }
}
